
import { message } from 'antd';

/**
 * 校验上传文件类型\大小
 * @param file 
 * @param type 图片(png|jpg)、音频(MP3|ogv|MPEG|AIFF|CD|WAVE)、视频(ogg|ogv|MPEG|AVI|ASF|MOV|WMV)、文档(pdf)
 * @returns 
 */
export const checkUploadFile = (file:any, type:string) => {
    console.log(type)
    let isUploadFile, typeName, fileFormat;
    const isLt2M = file.size / 1024 / 1024 < 2;
    switch(type) {
        case 'image':
            isUploadFile = file.type === 'image/jpeg' || file.type === 'image/png';
            typeName = '图片';
            fileFormat = 'JPG/PNG';
            break;
        case 'audio':
            isUploadFile = file.type === 'video/ogg';
            typeName = '音频';
            fileFormat = 'ogg/ogv';
            break;
        case 'video':
            isUploadFile = file.type === 'video/ogg';
            typeName = '视频';
            fileFormat = 'ogg/ogv';
            break;
        case 'document':
            isUploadFile = file.type === 'application/pdf';
            typeName = '文档';
            fileFormat = 'pdf';
            break;
    }
    if (!isUploadFile) {
        message.error(`${typeName}仅支持 ${fileFormat} 文件!`);
        return
    };
    if (!isLt2M) {
        message.error(`${typeName}不能超过 2MB!`);
        return
    }
    return isUploadFile && isLt2M;
}

/**
 * 获取对象中指定的key\value
 * @param obj 
 * @param arr 
 * @type ObjType 
 * @returns 
 */
type ObjType = {[key in string]: any}
export const pick = (obj:ObjType, arr:Array<string>):ObjType => {
    const result:ObjType = {}
    Object.keys(obj).forEach(item=>{
        if(arr.includes(item)) result[item] = obj[item]
    })
    return result
}

export type limitNumberValType = number|string|undefined
export const limitNumber = (value:limitNumberValType) => {
    if (typeof value === 'string') {
      return !isNaN(Number(value)) ? value.replace(/^(0+)|[^\d]/g, '') : ''
    } else if (typeof value === 'number') {
      return !isNaN(value) ? String(value).replace(/^(0+)|[^\d]/g, '') : ''
    } else {
      return ''
    }
}